package com.client;

import com.utils.LogUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;

/**
 * @author zyf
 */
public class Client extends LogUtil {

    // url为请求的路径
    private String url;

    private CloseableHttpClient HttpClient = HttpClientBuilder.create().build();

    private static Client singleClient = null;

    public Client() {
    }

    /**
     * 伪单例
     *
     * @return
     */
    public static Client getSingleInstance() {
        synchronized (Client.class) {
            if (singleClient == null) {
                singleClient = new Client();
                return singleClient;
            } else {
                return singleClient;
            }
        }
    }

    /**
     * get请求区块链数据
     *
     * @return HttpResponse
     */
    public HttpResponse doGet() {
        HttpGet get = new HttpGet(url);
        HttpResponse response = null;
        try {
            response = HttpClient.execute(get);
        } catch (Exception ex) {
            logMsg(LogType.Error, ex.getMessage());
            ex.printStackTrace();
        }
        return response;
    }

    /**
     * post交易到RepChain
     *
     * @param json 提交的数据
     * @return HttpResponse
     */
    public HttpResponse doPost(String json) {
        HttpPost post = new HttpPost(url);
        HttpResponse response = null;
        try {
            StringEntity stringEntity = new StringEntity(json);
            stringEntity.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            stringEntity.setContentType("application/json");
            post.setEntity(stringEntity);
            response = HttpClient.execute(post);
        } catch (Exception ex) {
            logMsg("Error", ex.getMessage());
            ex.printStackTrace();
        }
        return response;
    }

    /**
     * close Client
     */
    public void close() {
        if (HttpClient != null) {
            try {
                HttpClient.close();
            } catch (IOException ioEx) {
                logMsg(ERROR, "关闭client出现异常：{}", ioEx.getMessage());
                ioEx.printStackTrace();
            }
        }
    }


    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public CloseableHttpClient getHttpClient() {
        return HttpClient;
    }
}
